from twisted.words.protocols import irc
from twisted.internet import reactor, protocol
import sys, os, commands, string,time

class SVNBot_Logger:
	def __init__(self,file):
		self.file=file

	def log(self,message):
		timestamp=time.strftime("[%Y/%m/%d %H:%M:%S]", time.localtime(time.time()))
		self.file.write('%s %s\n' %(timestamp,message))
		self.file.flush()
	
	def close(self):
		self.file.close()

class SVNBot(irc.IRCClient):
	nickname="muktinbot"
	challenge="is identified to services "
	user="None"
	runcommand="False"
	committers=["jeevan_ullas","jeevan_ullas_","ksivaji","sivaji","sivaji_","sanjayb","kidfoo","deepsa","deepsa_","krish"]
	code="320"

	def parsemsg(self,s):
 	    prefix = ''
 	    trailing = []
 	    if not s:
 	        raise IRCBadMessage("Empty line.")
 	    if s[0] == ':':
 	        prefix, s = s[1:].split(' ', 1)
 	    if s.find(' :') != -1:
 	        s, trailing = s.split(' :', 1)
 	        args = s.split()
 	        args.append(trailing)
 	    else:
 	        args = s.split()
 	    command = args.pop(0)
 	    return prefix, command, args

	def connectionMade(self):
		irc.IRCClient.connectionMade(self)
		self.logger = SVNBot_Logger(open(self.factory.filename,"a"))

	def connectionLost(self,reason):
		irc.IRCClient.connectionLost(self,reason)
		self.logger.close()

	def signedOn(self):
		self.join(self.factory.channel)

	def kickedFrom(self,channel,kicker,message):
		self.signedOn()
	
	def privmsg(self,sender,recip,message):
		sender=sender.split('!',1)[0]
		self.logger.log("<%s> %s" % (sender,message + " " + recip))
		self.user=sender
		if message=="!svnupdate" and (sender in self.committers):
			self.sendLine('whois '+sender)
			self.runcommand=True
		elif message=="!svn":
                        self.msg(recip,"svn checkout https://muktin.googlecode.com/svn/trunk/ muktin")

	def lineReceived(self, line):
		irc.IRCClient.lineReceived(self,line)
		self.prefix, self.command, self.params = self.parsemsg(line)
		#print self.prefix, self.command, self.params
		if self.command==self.code and self.params[1]==self.user and self.params[2]==self.challenge and self.runcommand==True:
			self.runcommand=False
			s=commands.getoutput('svn update')
			for line in s.split('\n'):
				self.msg(self.user,line)

class SVNBotFactory(protocol.ClientFactory):
	protocol=SVNBot
	
	def __init__(self,channel,filename):
		self.channel=channel
		self.filename=filename
		
	def clientConnectionLost(self,connector,reason):
		print "Connection Lost"
		reactor.stop()
	
	def clientConnectionFailed(self,connector,reason):
		print "Connection Failed %s" %reason
		reactor.stop()

if __name__=='__main__':
	example=SVNBotFactory(sys.argv[1],'logfile.txt')
	
	reactor.connectTCP("irc.freenode.net",6667,example)
	reactor.run()
